package nori6_server_controllers;
import java.io.IOException;
import java.net.*;

public class NetworkController implements Runnable
{
	private int m_PortNumber;
	
	public NetworkController(int PortNumber)
	{
		m_PortNumber = PortNumber;
	}
	
	@Override
	public void run()
	{
		ServerSocket serverSocket = null;
		try
		{
			serverSocket = new ServerSocket(m_PortNumber);
			serverSocket.setSoTimeout(5000);			
		}
		catch(IOException e)
		{
			System.out.println("Failed to open socket. " + e.getMessage());
			System.exit(1);
		}
		
		System.out.println("Listening on port " + m_PortNumber + ".");
	
		while(Thread.currentThread().isInterrupted() == false)
		{
			try
			{
				Socket client = serverSocket.accept();
				System.out.println("Connected to client  " + client.getInetAddress().toString());
				MessageController msgc = new MessageController(client);
				msgc.run();
			}
			catch(IOException e)
			{
				System.out.println("Client connection failed. " + e.getMessage());
			}
		}
		
		System.out.println("Closing server socket");
	}
}
